package com.peking.donations.base.util;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;

/**
 * User: zhujp Date: 2016/2/26 15:41
 * <p/>
 * Version: 1.0 To change this templates use File | Settings | File Templates.
 */
public class Signature {

    private static Logger logger = LoggerFactory.getLogger(Signature.class);

    /**
     * 签名算法
     *
     * @param o
     *            要参与签名的数据对象
     * @return 签名
     * @throws IllegalAccessException
     */
    public static String getSign(Object o, String payKey) throws IllegalAccessException {
        ArrayList<String> list = new ArrayList<>();
        Class cls = o.getClass();
        Field[] fields = cls.getDeclaredFields();
        for (Field f : fields) {
            f.setAccessible(true);
            if (f.get(o) != null && f.get(o) != "") {
                list.add(f.getName() + "=" + f.get(o) + "&");
            }
        }
        int size = list.size();
        String[] arrayToSort = list.toArray(new String[size]);
        Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) {
            sb.append(arrayToSort[i]);
        }
        String result = sb.toString();
        result += "key=" + payKey;
        logger.debug("微信签名前的拼接字符串为[{}]", result);
        result = DigestUtils.md5Hex(result).toUpperCase();
        logger.debug("微信签名后为[{}]", result);
        return result;
    }

    /**
     * md5加密 签名
     * 
     * @param map
     * @param payKey
     * @return
     */
    public static String getSign(Map<String, String> map, String payKey) {
        ArrayList<String> list = new ArrayList<String>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (entry.getValue() != "") {
                list.add(entry.getKey() + "=" + entry.getValue() + "&");
            }
        }
        int size = list.size();
        String[] arrayToSort = list.toArray(new String[size]);
        Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) {
            sb.append(arrayToSort[i]);
        }
        String result = sb.toString();
        result += "key=" + payKey;
        logger.debug("签名前：" + result);
        result = DigestUtils.md5Hex(result).toUpperCase();
        logger.debug("签名后：" + result);
        return result;
    }
}
